package top.ruanlitao.shortlink.project.mq.rocketmq.producer;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;
import top.ruanlitao.shortlink.project.mq.producer.ShortLinkStatsSaveProducer;

import java.util.Map;
import java.util.UUID;

/**
 * 短链接监控状态保存消息队列生产者
 */
@ConditionalOnProperty(prefix = "short-link.message-queue", name = "type", havingValue = "rocketmq", matchIfMissing = true)
@Component("rocketMQShortLinkStatsSaveProducer")
@RequiredArgsConstructor
@Slf4j
public class RocketMQShortLinkStatsSaveProducer implements ShortLinkStatsSaveProducer {

    private final RocketMQTemplate rocketMQTemplate;

    @Value("${rocketmq.topic.stats-save}")
    private String statsSaveTopic;

    /**
     * 发送保存统计信息的消息
     */
    @Override
    public void send(Map<String, String> producerMap) {
        String keys = UUID.randomUUID().toString();
        producerMap.put("keys", keys);
        // 构造消息
        Message<Map<String, String>> message = MessageBuilder
                .withPayload(producerMap)
                .setHeader(RocketMQHeaders.KEYS, keys)
                .build();
        // 发送消息
        rocketMQTemplate.asyncSend(statsSaveTopic, message, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                log.info("统计数据成功发送至【RocketMQ】消息队列，发送结果为：{}", sendResult);
            }

            @Override
            public void onException(Throwable throwable) {
                log.info("统计数据发送至【RocketMQ】消息队列失败，异常信息为：{}", throwable.getMessage());
            }
        });
    }
}
